package ecustom.finance.actions;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;

import ecustom.clients.k3client.K3WebApiClient;
import ecustom.clients.k3client.entities.ERPPAYBILLReq;
import ecustom.clients.k3client.entities.ERPPAYBILLReq.FPAYBILLENTRY;
import ecustom.clients.util.JsonUtil;
import ecustom.common.AbstractAction;
import ecustom.common.CustomMap;
import ecustom.common.conn.DB;
import ecustom.common.servicelog.bean.ServiceLogBean;
import ecustom.common.util.CustomUtil;
import ecustom.finance.bean.FinanceBean;
import weaver.file.Prop;
import weaver.soa.workflow.request.DetailTable;
import weaver.soa.workflow.request.Property;
import weaver.soa.workflow.request.RequestInfo;
import weaver.soa.workflow.request.Row;

/**
* @author 作者:Gcc
* @createDate 创建时间：Aug 14, 2023 11:48:17 PM
* 差旅报销-推送ERP付款单
*/
public class CLBXAction extends AbstractAction{
	
	private static final Logger log = Logger.getLogger(AbstractAction.class); 

	@Override
	public void process(RequestInfo requestInfo) throws Exception {
		Property[] mainFields = requestInfo.getMainTableInfo().getProperty();
		
		if(super.getMainInteger(mainFields, "sftserp") == 1) return;	// 是否推送ERP：0:是；否：1
		if(CustomUtil.isNotBlank(super.getMainString(mainFields, "erpNumber"))) return;	// ERP编码为空的情况，不重复推送给ERP
		
		handlERPData(requestInfo, mainFields);
	}
	
	public void handlERPData(RequestInfo requestInfo, Property[] mainFields) throws Exception {
		ServiceLogBean logBean = new ServiceLogBean("CLBXAction", "ecustom.finance.actions.CLBXAction-差旅报销-推送ERP付款单",  "K3Cloud", "", System.currentTimeMillis());
		String formid = Prop.getPropValue("ecustom", "k3.fkd.formid");
		
		ERPPAYBILLReq req = setAYBILLReq(requestInfo, mainFields);
		log.info("outReq"+JsonUtil.toJson(req));
		Map<String, Object> erpResult = K3WebApiClient.saveData(logBean, req, formid);
		
		Integer requestId = requestInfo.getRequestManager().getRequestid();
		int formId = requestInfo.getRequestManager().getFormid();
		updateTable(formId, requestId, erpResult);
	}
	
	public ERPPAYBILLReq setAYBILLReq(RequestInfo requestInfo, Property[] mainFields) throws Exception, Exception {
		String fqzz = FinanceBean.getERPOrgNumber(super.getMainStringCK(mainFields, "fqzz", "发起组织不能为空！"));	// 所属公司
		String wldwlx = super.getMainStringCK(mainFields, "wldwlx", "往来单位类型不能为空！");	// 往来单位类型
		String wldw = FinanceBean.getERPWldw(super.getMainStringCK(mainFields, "wldw", "往来单位不能为空！"), wldwlx);	// 往来单位
		String skdwlx = super.getMainStringCK(mainFields, "skdwlx", "收款单位类型不能为空！");	// 往来单位类型
		String skdw = FinanceBean.getERPWldw(super.getMainStringCK(mainFields, "skdw", "收款单位不能为空！"), skdwlx);	// 往来单位
		String bb = super.getMainStringCK(mainFields, "jsbb", "结算币别不能为空！");	// 结算币别，表单固定人民币
		
		String sfwlfy = super.getMainStringCK(mainFields, "sfwlfy", "是否往来费用不能为空！");	// 是否往来费用
		if("0".equals(sfwlfy)) {
			sfwlfy = "1";
		}else if("1".equals(sfwlfy)){
			sfwlfy = "2";
		}
		ERPPAYBILLReq repPUR = new ERPPAYBILLReq();   
		repPUR.setIsAutoSubmitAndAudit("true");	// 审核
		repPUR.getModel().setFID(0);	// 实体主键，有实体主键为修改操作，没有则新建
		repPUR.getModel().getFBillTypeID().put("FNUMBER", "FKDLX04_SYS");
		repPUR.getModel().setFDATE(CustomUtil.getStringDate());	// 单据时间
		repPUR.getModel().setFCONTACTUNITTYPE(wldwlx);	// 往来单位类型
		repPUR.getModel().getFCONTACTUNIT().put("FNumber", wldw);	// 往来单位
		repPUR.getModel().setFRECTUNITTYPE(skdwlx);	// 收款单位类型
		repPUR.getModel().getFRECTUNIT().put("FNumber", skdw);	// 收款单位
		repPUR.getModel().getFCURRENCYID().put("FNumber", bb);	// 币别
		repPUR.getModel().getFSETTLEORGID().put("FNumber", fqzz);	// 结算组织
		repPUR.getModel().getFPAYORGID().put("FNumber", fqzz);	// 付款组织
		repPUR.getModel().getFSETTLECUR().put("FNUMBER", bb);	// 结算币别
		repPUR.getModel().setF_SZXY_OARequestID(requestInfo.getRequestManager().getRequestid()+"");
		repPUR.getModel().getFSETTLEMAINBOOKID().put("FNUMBER", "PRE001");	// 结算本位币，币别
		repPUR.getModel().setF_SZXY_Combo(sfwlfy);	// 是否往来费用
		
		repPUR.getModel().setFDOCUMENTSTATUS("Z");	// 单据状态：固定-Z
		repPUR.getModel().setFBUSINESSTYPE("3");	// 业务类型：固定-3
		repPUR.getModel().setFCancelStatus("A");	// 作废状态，默认：A
		// 
		repPUR.getModel().setFPAYBILLENTRY(getFPAYBILLENTRY(requestInfo, mainFields, repPUR));
		return repPUR;
	}
	
	/**
	 * TODO 
	 * 赋值明细表
	 * @param requestInfo
	 * @param mainFields
	 * @param jsfs	结算方式
	 * @param fkyt	付款用途
	 * @return
	 * @throws Exception
	 * @throws Exception
	 */
	public List<FPAYBILLENTRY> getFPAYBILLENTRY(RequestInfo requestInfo, Property[] mainFields, ERPPAYBILLReq repPUR) throws Exception, Exception {
		Integer requestid = requestInfo.getRequestManager().getRequestid();
		int formid = requestInfo.getRequestManager().getFormid();
		String jsfs = FinanceBean.getERPJsfs(super.getMainStringCK(mainFields, "jsfs", "结算方式不能为空！"));	// 结算方式
		String fkyt = FinanceBean.getERPFkyt(super.getMainString(mainFields, "fkyt"));	// 付款用途
		String dfyhzh = super.getMainString(mainFields, "dfyhzh");	// 对方银行账号
		String dfyhmc = super.getMainString(mainFields, "dfyhmc");	// 对方账户名称
		String yxwd = super.getMainString(mainFields, "yxwd");	// 对方银行网点
		
		List<String> addrssList = new ArrayList<String>();
		DetailTable  detailTable = requestInfo.getDetailTableInfo().getDetailTable(0);
		List<FPAYBILLENTRY> listFEntity = new ArrayList<FPAYBILLENTRY>();
		for(Row row: detailTable.getRow()) {
//			String qsdd = super.getCellString(row, "qsdd");	// 起始地点
//			String qsdd2 = super.getCellString(row, "qsdd2");	//  结束地点
//			if(!addrssList.contains(qsdd)) {
//				addrssList.add(qsdd);
//			}
//			if(!addrssList.contains(qsdd2)) {
//				addrssList.add(qsdd2);
//			}
			
			// 新调整，解决旧字段没有数据的问题
			String qsdd3 = getCs(super.getCellInteger(row, "qsdd3"));	// 起始地点
			String qsdd4 = getCs(super.getCellInteger(row, "qsdd4"));	//  结束地点
			if(!addrssList.contains(qsdd3)) {
				addrssList.add(qsdd3);
			}
			if(!addrssList.contains(qsdd4)) {
				addrssList.add(qsdd4);
			}
			
			String fycdbm = FinanceBean.getERPDeptNumberV2(super.getCellString(row, "fycdbm"));	// 费用承担部门
			String fyxm = FinanceBean.getERPFyxm(super.getCellString(row, "fyxm"));	// 费用项目
			String wfyxzh = FinanceBean.getERPYhzh(super.getCellString(row, "wfyxzh"));	// 我方银行账号
			Double fyje = super.getCellDoubleValue(row, "fyje");	// 费用金额
			String sklx = super.getCellString(row, "sklx");	// 收款类型
			String rzlx = super.getCellString(row, "rzlx");	// 入账类型
			Double fkje = super.getCellDoubleValue(row, "fkje");	// 付款金额
			Double yfje = super.getCellDoubleValue(row, "yfje");	// 应付金额
			String invoiceNumbers = super.getCellString(row, "fph");	// 发票号
			Double hl = super.getCellDoubleValue(row, "hl");	// 应付金额
			
			FPAYBILLENTRY entry = new FPAYBILLENTRY();
			entry.getFSETTLETYPEID().put("FNumber", jsfs);	// 结算方式
			entry.getFPURPOSEID().put("FNumber", fkyt);	// 付款用途
			if(CustomUtil.isNotBlank(fyxm)) {
				entry.getFCOSTID().put("FNumber", fyxm);	// 费用项目
			}
			if(CustomUtil.isNotBlank(fycdbm)) {
				entry.getFEXPENSEDEPTID_E().put("FNumber", fycdbm);	// 费用承担部门
			}
			if(CustomUtil.isNotBlank(wfyxzh)) {
				entry.getFACCOUNTID().put("FNumber", wfyxzh);	// 我方银行账号
			}
			entry.setFOPPOSITEBANKACCOUNT(dfyhzh);	// 对方银行账号
			entry.setFOPPOSITECCOUNTNAME(dfyhmc);	// 对方账户名称
			if(CustomUtil.isNotBlank(yxwd)) {
				entry.getFBankDetail().put("FNUMBER", yxwd);	// 银行网点
			}
			entry.setFCOMMENT("");	// 备注
			entry.setFRecType(sklx);	// 收款类型
			entry.setFPOSTDATE(CustomUtil.getStringDate());	// 登账日期
			entry.setFRuZhangType(rzlx);	// 入账类型
			
			// 发票费用明细
			List<FPAYBILLENTRY> invoiceDetail = handlInvoiceDetail(invoiceNumbers, entry, sklx, rzlx);
			
			entry.setF_SZXY_Amount(fyje-entry.getF_SZXY_Amount1());	// 费用金额
			entry.setFPAYAMOUNTFOR_E(fkje-entry.getF_SZXY_Amount1());	// 付款金额
			entry.setFPAYTOTALAMOUNTFOR(yfje-entry.getF_SZXY_Amount1());	// 应付金额
			entry.setF_SZXY_Amount1(0.0);	// 进项税
			log.info("invoiceDetail:"+JsonUtil.toJson(invoiceDetail));
			log.info("entry:"+JsonUtil.toJson(entry));
			listFEntity.add(entry);
			listFEntity.addAll(invoiceDetail);	// 将发票费用明细写入到ERP里面
		}
		// 2023-10-18调整备注：“【差旅费（内容）】” 
		String bz = "差旅费（"+FinanceBean.getCLBXDates(formid, requestid)+", "+CustomUtil.join(addrssList, ",")+"）";
		repPUR.getModel().setFREMARK(FinanceBean.subRemark(bz));		// 备注
		return listFEntity;
	}
	
	/**
	 * 处理发票费用明细
	 * @param invoiceNumbers
	 * @param entry 费用数据（赋值）
	 * @param sklx 入账类型
	 * @param rzlx
	 * @return
	 * @throws Exception
	 */
	private List<FPAYBILLENTRY> handlInvoiceDetail(String invoiceNumbers, FPAYBILLENTRY entry, String sklx, String rzlx) throws Exception {
		List<FPAYBILLENTRY> invoiceDetail = new ArrayList<FPAYBILLENTRY>();
		Double taxSum = 0.0;
		List<CustomMap> invoiceMap = FinanceBean.getInvoiceData(invoiceNumbers);	// 发票号码
		if(CustomUtil.isNotBlank(invoiceMap)) {
			for(CustomMap map : invoiceMap) {
				Double tax = map.getDouble("DTAX");
				if(CustomUtil.isNotBlank(tax) && tax > 0) {
					FPAYBILLENTRY newEntry = new FPAYBILLENTRY();
					if(CustomUtil.isNotBlank(entry.getFSETTLETYPEID().get("FNumber"))) {
						newEntry.getFSETTLETYPEID().put("FNumber", entry.getFSETTLETYPEID().get("FNumber"));;	// 结算方式
					}
					if(CustomUtil.isNotBlank(entry.getFPURPOSEID().get("FNumber"))) {
						newEntry.getFPURPOSEID().put("FNumber", entry.getFPURPOSEID().get("FNumber"));;	// 付款用途
					}
					if(CustomUtil.isNotBlank(entry.getFCOSTID().get("FNumber"))) {
						newEntry.getFCOSTID().put("FNumber", entry.getFCOSTID().get("FNumber"));;	// 费用项目
					}
					if(CustomUtil.isNotBlank(entry.getFEXPENSEDEPTID_E().get("FNumber"))) {
						newEntry.getFEXPENSEDEPTID_E().put("FNumber", entry.getFEXPENSEDEPTID_E().get("FNumber"));;	// 费用承担部门
					}
					if(CustomUtil.isNotBlank(entry.getFACCOUNTID().get("FNumber"))) {
						newEntry.getFACCOUNTID().put("FNumber", entry.getFACCOUNTID().get("FNumber"));;	// 我方银行账号
					}
					newEntry.setFOPPOSITEBANKACCOUNT(entry.getFOPPOSITEBANKACCOUNT());	// 对方银行账号
					newEntry.setFOPPOSITECCOUNTNAME(entry.getFOPPOSITECCOUNTNAME());	// 对方账户名称
					newEntry.setFCOMMENT("");	// 备注
					newEntry.setFRecType(sklx);	// 收款类型
					newEntry.setFPOSTDATE(CustomUtil.getStringDate());	// 登账日期
					newEntry.setFRuZhangType(rzlx);	// 入账类型
					FinanceBean.setInputTax(newEntry, map.getString("INVOICETYPE"));	// 进项税类型：0：税一；1：税二
					
					newEntry.setF_SZXY_NoteInvNO(map.getString("INVOICENUMBER"));	// 备注发票号
					
					newEntry.setF_SZXY_Amount(null);	// 费用金额
					newEntry.setF_SZXY_Amount1(tax);	// 进项税，传发票的增值税
					newEntry.setFPAYTOTALAMOUNTFOR(null);	// 应付金额
					invoiceDetail.add(newEntry);
					log.info("invoiceDetail-newEntry:"+JsonUtil.toJson(newEntry));
					taxSum = CustomUtil.add(taxSum, tax);	// 进项税累加
				}
				
			}
		}
		
		entry.setF_SZXY_Amount1(taxSum);	// 合计进项税，传发票的增值税
		return invoiceDetail;
	}
	
	private int updateTable(Integer formId, Integer requestId, Map<String, Object> erpResult) throws SQLException {
		Integer erpFID = CustomUtil.getInteger(erpResult.get("FID"));
		String erpNumber = CustomUtil.getString(erpResult.get("Number"));
		String tableName = "FORMTABLE_MAIN_" + Math.abs(formId);
		String updateSql = "UPDATE "+tableName+" SET ERPFID=?, ERPNUMBER=? WHERE REQUESTID=?";
		int i = DB.conn().executeUpdate(updateSql, erpFID, erpNumber, requestId);
		return i;
	}
	
	private String getCs(Integer id) throws Exception {
		String sql = "SELECT CS FROM UF_CSXXB WHERE ID=?";
		String csStr = DB.conn().getString(sql, id);
		return csStr+"";
	}
	

}
